<?php
defined('BASEPATH') OR exit('No direct script access allowed');
include_once 'Base.php';
class Systems extends Base
{
    //管理员列表
    public function administrator()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            show_error('暂无权限');
        }

        $wh = ' u.status <> 2 ';

        $request = $this->input->get(['start_time','end_time','username']);

        $start_time = '';
        if($request['start_time']){
            $start_time = strtotime($request['start_time']);
            $wh .= ' and u.created_at >= '.$start_time;
            $start_time = date('Y-m-d',$start_time);
        }

        $end_time = '';
        if($request['end_time']){
            $end_time = strtotime($request['end_time']);
            $end_time = (int)$end_time+86399;
            $wh .= ' and u.created_at <= '.$end_time;
            $end_time = date('Y-m-d',$end_time);
        }

        $username = '';
        if($request['username']){
            $username = (string)$request['username'];
            $wh .= '  and u.nickname like "%'.$username.'%"';
        }

        $this->load->database();
        $query = $this->db->query('SELECT u.*,r.name AS r_name,r.id AS r_id FROM admin_user AS u 
LEFT JOIN admin_user_role z ON z.user_id=u.id 
LEFT JOIN admin_role r ON r.id=z.role_id 
WHERE '.$wh);

        $list = $query->result_array();

        $viewData = [
            'list' => $list,
            'menus' => $this->redis[$this->account]['authority'] ? : [],
            'class' => __CLASS__,
            'function' => __FUNCTION__,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'username' => $username,
            'account' => $this->account
        ];
        $this->load->view('Systems/administrator',$viewData);
    }

    //添加管理员表单
    public function administrator_add()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            show_error('暂无权限');
        }
        $this->load->database();

        $query = $this->db->query('SELECT NAME,id FROM admin_role WHERE STATUS=1');
        $list = $query->result_array();

        $this->load->view('Systems/administrator_add',['list'=>$list]);
    }

    //添加管理员操作
    public function administrator_do()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }

        if ($this->input->is_ajax_request()) {
            $post = $this->input->post(['account','nickname','password','password2','role_id'],true);
            $account = $post['account'];
            $nickname = $post['nickname'];
            $password = $post['password'];
            $repassword = $post['password2'];
            $role_id = $post['role_id'];

            $account_length = strlen($account);
            $password_length = strlen($password);
            if($account_length < 4 || $account_length > 12 || $password_length < 6 || $password_length > 16 || ($password !== $repassword)){
                $this->ajax_return(0);
            }

            $this->load->database();//加载数据库
            $this->db->trans_begin();//开启事务
            try {
                $result = $this->db->query('insert into admin_user (nickname,account,password,created_at,updated_at) values("'.$nickname.'","'.$account.'","'.md6($password).'","'.time().'","'.time().'")');
                if($result && $role_id){
                    //添加角色
                    $this->db->query('insert into admin_user_role (role_id,user_id) values("'.$role_id.'","'.$this->db->insert_id().'")');
                }
            } catch (\Exception $e) {
                log_message('error', $e->getMessage());
                $this->db->trans_rollback();//回滚
                $this->ajax_return(2);
            }
            $this->db->trans_commit();//提交事务
            $this->ajax_return(1);
        }
    }

    //管理员修改页面
    public function administrator_edit()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            show_error('暂无权限');
        }
        $id = $this->input->get('id');

        $this->load->database();
        $query = $this->db->query('SELECT u.id,u.nickname,u.account,ur.user_id,ur.role_id FROM admin_user u INNER JOIN admin_user_role ur ON ur.user_id=u.id  WHERE u.id="'.$id.'"');
        $vo = $query->result_array();
        $query = $this->db->query('select id,name from admin_role where status=1');
        $roles = $query->result_array();
        $result = [
            'vo' => $vo[0],
            'roles' => $roles
        ];
        $this->load->view('systems/administrator_edit',$result);
    }

    //管理员修改操作
    public function administrator_edit_do()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }

        if($this->input->is_ajax_request()){
            $request = $this->input->post(['id','nickname','password','password2','role_id'],true);

            $this->load->database();//加载数据库
            $this->db->trans_begin();//开启事务
            try{
                $id = $request['id'];
                $query  = $this->db->query('select id,nickname,account from admin_user where id='.$id.' limit 1');
                $user_info = $query->result_array();
                $user_info = $user_info[0];
                if($request['password'] && $request['password'] == $request['password2']){
                    $pass = md6($request['password']);
                    $this->db->query('update admin_user set nickname="'.$request['nickname'].'",password="'.$pass.'",updated_at='.time().' where id='.$id);
                }else{
                    $this->db->query('update admin_user set nickname="'.$request['nickname'].'",updated_at='.time().' where id='.$id);
                }

                $del = $this->db->query('delete from admin_user_role where user_id='.$id);
                if($del){
                    $this->db->query('insert into admin_user_role (user_id,role_id) values('.$id.','.$request['role_id'].')');
                }
                if($this->cache->redis->strlen($user_info['account'])){
                    $this->refresh_redis($user_info['account']);
                }
            }catch(\Exception $e){
                $this->db->trans_rollback();//回滚
                $this->ajax_return(0);
            }
            $this->db->trans_commit();//提交
            $this->ajax_return(1);
        }
    }

    //管理员状态修改
    public function administrator_status()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }

        if ($this->input->is_ajax_request()) {
            $request = $this->input->post(['id','status'],true);
            try {
                $this->load->database();
                $this->db->query('update admin_user set status='.$request['status'].' where id='.$request['id']);
            } catch (\Exception $e) {
                log_message('error',$e->getMessage());
                $this->ajax_return(0);
            }
            $this->ajax_return(1);
        }
    }

    //管理员删除操作
    public function administrator_del()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }

        if ($this->input->is_ajax_request()) {
            $id = $this->input->post('id',true);
            $this->load->database();
            try {
                if(is_array($id)){
                    $id = implode(',',$id);
                    $this->db->query('update admin_user set status=2 where id in ('.$id.')');
                }else{
                    $this->db->query('update admin_user set status=2 where id='.$id);
                }
            } catch (\Exception $e) {
                log_message('error',$e->getMessage());
                $this->ajax_return(0);
            }
            $this->ajax_return(1);
        }
    }

    //系统模块页面
    public function module()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            show_error('暂无权限');
        }

        $this->load->database();
        $query = $this->db->query('select * from admin_module where status<>2');
        $list = $query->result_array();
        $data = [
            'list' => $list,
            'function' => __FUNCTION__,
            'account' => $this->account,
            'menus' => $this->redis[$this->account]['authority'] ? : [],
        ];
        $this->load->view('Systems/module',$data);
    }

    //系统模块添加页
    public function module_add()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            show_error('暂无权限');
        }
        $this->load->view('Systems/module_add');
    }

    //系统模块添加处理
    public function module_do()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }

        if ($this->input->is_ajax_request()) {
            $request = $this->input->post(['module_name','sort','icon']);
            $this->load->database();
            try {
                $this->db->query('insert into admin_module (name,sort,icon) values("'.$request['module_name'].'",'.(int)$request['sort'].',"'.$request['icon'].'")');
            } catch (\Exception $e) {
                log_message('debug',$e->getMessage());
                $this->ajax_return(2);
            }
            $this->refresh_redis('all');
            $this->ajax_return(1);
        }
    }

    //系统模块状态修改
    public function module_status()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }

        if ($this->input->is_ajax_request()) {
            $this->load->database();
            $request = $this->input->post(['id','status'],true);
            try {
                $this->db->query('update admin_module set status='.$request['status'].' where id='.$request['id']);
            } catch (\Exception $e) {
                log_message('error',$e->getMessage());
                $this->ajax_return(0);
            }
            $this->refresh_redis('all');
            $this->ajax_return(1);
        }
    }

    //系统模块修改页
    public function module_edit()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            show_error('暂无权限');
            exit;
        }
        $id = $this->input->get('id');
        $this->load->database();
        $query = $this->db->query('select * from admin_module where id='.$id);
        $result = $query->result_array();
        $this->load->view('/Systems/module_edit',['vo'=>$result[0]]);
    }

    //解析sql update数组
    private function parseSet($arr)
    {
        if(is_array($arr)){
            $set = [];
            foreach($arr as $k=>$v){
                if(is_string($v)){
                    $set[] = $k.'="'.$v.'"';
                }else{
                    $set[] = $k.'='.$v;
                }
            }
            return implode(',',$set);
        }
    }
    //系统模块修改处理
    public function module_edit_do()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }

        if ($this->input->is_ajax_request()) {
            $request = $this->input->post(['id','name','icon','sort']);
            if(!$request['id']){
                $this->ajax_return(0);
            }
            $this->load->database();
            try {
                $this->db->query('update admin_module set name="'.$request['name'].'",icon="'.$request['icon'].'",'.$request['sort'].' where id='.$request['id']);
            } catch (\Exception $e) {
                log_message('error',$e->getMessage());
                $this->ajax_return(0);
            }
            $this->refresh_redis('all');
            $this->ajax_return(1);
        }
    }

    //系统模块删除
    public function module_del()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }

        if ($this->input->is_ajax_request()) {
            $id = $this->input->post('id',true);
            $this->load->database();
            try {
                $this->db->query('update admin_module set status=2 where id='.$id);
            } catch (\Exception $e) {
                log_message('error',$e->getMessage());
                $this->ajax_return(0);
            }
            $this->refresh_redis('all');
            $this->ajax_return(1);
        }
    }

    //分类页面
    public function classify()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            show_error('暂无权限');
        }

        $this->load->database();
        $query = $this->db->query('select c.*,m.name as m_name from admin_classify as c left join admin_module as m on c.group_id=m.id where c.status<>2');

        $list = $query->result_array();
        $data = [
            'list' => $list,
            'function' => __FUNCTION__,
            'account' => $this->account,
            'menus' => $this->redis[$this->account]['authority'] ? : [],
        ];

        $this->load->view('Systems/classify',$data);
    }

    //分类添加页面
    public function classify_add()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            show_error('暂无权限');
        }

        $this->load->database();
        $query = $this->db->query('select id,name from admin_module where status<>2');
        $result = $query->result_array();

        $this->load->view('Systems/classify_add',['modules'=>$result]);
    }

    //添加分类操作
    public function classify_do()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }

        if ($this->input->is_ajax_request()) {
            $request = $this->input->post(['classify_name','group_id','sort','route','func'],true);
            $this->load->database();
            try {

                if (!$this->db->query('select count(*) from admin_module where status<>2 and id='.$request['group_id'])) {
                    $this->ajax_return(0);
                }
                $request['sort'] = $request['sort'] ? : 0;
                $this->db->query('insert into admin_classify (name,sort,group_id,route,func,created_at,updated_at) values("'.$request['classify_name'].'",'.$request['sort'].','.$request['group_id'].',"'.$request['route'].'","'.$request['func'].'",'.time().','.time().') ');
            } catch (\Exception $e) {
                log_message('error',$e->getMessage());
                $this->ajax_return(0);
            }
            $this->refresh_redis('all');
            $this->ajax_return(1);
        }
    }

    //分类状态修改
    public function classify_status()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }
        if ($this->input->is_ajax_request()) {
            $request = $this->input->post(['id','status']);
            $this->load->database();
            try {
                $this->db->query('update admin_classify set status='.$request['status'].' where id='.$request['id']);
            } catch (\Exception $e) {
                log_message('error',$e->getMessage());
                $this->ajax_return(0);
            }
            $this->ajax_return(1);
        }
    }

    //分类修改页面
    public function classify_edit()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            show_error('暂无权限');
        }
        $id = $this->input->get('id');
        $this->load->database();
        $query = $this->db->query('select * from admin_classify where id='.$id);
        $res = $query->result_array();
        $res = $res[0];
        $query2 = $this->db->query('select id,name from admin_module where status<>2');
        $modules = $query2->result_array();
        $this->load->view('Systems/classify_edit',['vo'=>$res,'modules'=>$modules]);
    }

    //分类修改处理
    public function classify_edit_do()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }

        if ($this->input->is_ajax_request()) {
            $request = $this->input->post(['id','classify_name','group_id','sort','route','func'],true);
            $this->load->database();
            try {
                if (!$request['id']) {
                    $this->ajax_return(0);
                }
                $this->db->query('update admin_classify set name="'.$request['classify_name'].'",group_id='.$request['group_id'].',sort='.$request['sort'].',route="'.$request['route'].'",func="'.$request['func'].'" where id='.$request['id']);

            } catch (\Exception $e) {
               log_message('error',$e->getMessage());
               $this->ajax_return(0);
            }
            $this->ajax_return(1);
        }
    }

    //分类删除
    public function classify_del()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }

        if ($this->input->is_ajax_request()) {
            $id = $this->input->post('id');
            $this->load->database();
            try {
                $this->db->query('update admin_classify set status=2 where id='.$id);
            } catch (\Exception $e) {
                log_message('error',$e->getMessage());
                $this->ajax_return(0);
            }
            $this->ajax_return(1);
        }
    }


    //角色页面
    public function role()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
           show_error('暂无权限');
        }

        $this->load->database();
        $query = $this->db->query('select * from admin_role where status<>2');
        $list = $query->result_array();
        $data = [
            'list' => $list,
            'function' => __FUNCTION__,
            'account' => $this->account,
            'menus' => $this->redis[$this->account]['authority'] ? : [],
        ];
        $this->load->view('Systems/role',$data);
    }

    //角色添加页面
    public function role_add()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            show_error('暂无权限');
        }
        $this->load->view('Systems/role_add');
    }

    //角色添加操作
    public function role_do()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }

        if ($this->input->is_ajax_request()) {
            $request = $this->input->post(['role_name','remark'],true);
            $this->load->database();
            try {
                $this->db->query('insert into admin_role (name,remark,create_user) values("'.$request['role_name'].'","'.$request['remark'].'","'.$this->account.'")');
            } catch (\Exception $e) {
                log_message('error',$e->getMessage());
                $this->ajax_return(0);
            }
            $this->ajax_return(1);
        }
    }

    //分配权限
    public function role_authority()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            show_error('暂无权限');
        }

        $id = $this->input->get('id');
        $list = $this->redis['authority'];
        $this->load->database();
        $query = $this->db->query('select * from admin_role_authority where role_id='.$id);
        $arr = $query->result_array();

        foreach($list as $k => &$v){
            foreach($v['arr'] as $kk => &$vv){
                foreach($vv['arr'] as $kkk => &$vvv){
                    foreach($arr as $z => $x){
                        if($vvv['classify_id'] == $x['classify_id']){
                            $vv['is_check'] = 1;
                            if($vvv['id'] == $x['authority_id']){
                                $vvv['is_check'] = 1;
                            }
                        }
                    }
                }
            }
        }

        $que = $this->db->query('select name from admin_role where id='.$id);
        $name = $que->result_array();
        $name = $name[0]['name'];

        $data = [
            'list' => $list,
            'function' => 'role',
            'name' => $name,
            'role_id' => $id,
            'account' => $this->account,
            'menus' => $this->redis[$this->account]['authority'] ? : [],
        ];
        $this->load->view('Systems/role_authority',$data);
    }

    //处理权限分配
    public function role_authority_do()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }

        if($this->input->is_ajax_request()){
            $post = $this->input->post('sub');

            $role_id = $this->input->post('role_id');
            $create_list = [];
            $insert = '(role_id,module_id,classify_id,authority_id) values';
            $key = 0;
            $is_insert = false;
            foreach($post as $k => $v){
                $m_id = $k;
                foreach($v['arr'] as $kk => $vv){
                    $c_id = $kk;
                    foreach($vv['arr'] as $kkk => $vvv){
                        //$create_list[] = ['role_id'=>$role_id,'module_id'=>$m_id,'classify_id'=>$c_id,'authority_id'=>$vvv['authority_id']];
                        if($role_id && $m_id && $c_id && $vvv['authority_id']){
                            $is_insert = true;
                        }
                        if($key) $insert.=',';
                        $insert .= ' ('.$role_id.','.$m_id.','.$c_id.','.$vvv['authority_id'].')';
                        $key++;
                    }
                }
            }

            $this->load->database();//加载数据库
            $this->db->trans_begin();//开启事务
            try{
                $this->db->query('delete from admin_role_authority where role_id='.$role_id);
                if($is_insert){
                    $this->db->query('insert into admin_role_authority '.$insert);
                }
                $this->refresh_redis('all');
            }catch(\Exception $e){
                log_message('error',$e->getMessage());
                $this->db->trans_rollback();//回滚
                $this->ajax_return(0);
            }
            $this->db->trans_commit();//回滚
            $this->ajax_return(1);
        }
    }


    //角色修改页面
    public function role_edit()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            show_error('暂无权限');
        }

        $id = $this->input->get('id');
        $this->load->database();
        $query = $this->db->query('select * from admin_role where id='.$id);
        $query = $query->result_array();
        $vo = $query[0];
        $this->load->view('Systems/role_edit',['vo'=>$vo]);
    }

    //角色修改操作
    public function role_edit_do()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            show_error('暂无权限');
        }

        if ($this->input->is_ajax_request()) {
            $request = $this->input->post(['id','role_name','remark']);
            $this->load->database();
            try {
                $this->db->query('update admin_role set name="'.$request['role_name'].'",remark="'.$request['remark'].'" where id='.$request['id']);

            } catch (\Exception $e) {
                log_message('error',$e->getMessage());
                $this->ajax_return(0);
            }
            $this->ajax_return(1);
        }
    }

    //角色删除
    public function role_del()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }
        if ($this->input->is_ajax_request()) {
            $id = $this->input->post('id');
            $this->load->database();
            try {
                $this->db->query('update admin_role set status=2 where id='.$id);
            } catch (\Exception $e) {
                log_message('error',$e->getMessage());
                $this->ajax_return(0);
            }
            $this->ajax_return(1);
        }
    }

    //权限页面
    public function authority()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            show_error('暂无权限');
        }

        $this->load->database();
        $query = $this->db->query('SELECT a.*,m.name AS m_name,c.name AS c_name
FROM admin_authority AS a
LEFT JOIN admin_module AS m ON a.module_id=m.id
LEFT JOIN admin_classify AS c ON c.id=a.classify_id');
        $list = $query->result_array();
        $data = [
            'list' => $list,
            'function' => __FUNCTION__,
            'account' => $this->account,
            'menus' => $this->redis[$this->account]['authority'] ? : [],
        ];
        $this->load->view('Systems/authority',$data);
    }


    //权限增加页面
    public function authority_add()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            show_error('暂无权限');
        }
        $this->load->database();
        $query = $this->db->query('select id,name from admin_module where status<>2');
        $modules = $query->result_array();

        $query2 = $this->db->query('select id,name,group_id from admin_classify where status<>2');
        $classify = $query2->result_array();

        //拼接模块分类树状图
        $list = [];
        foreach($modules as $k => $v){
            foreach($classify as $kk => $vv){
                if($v['id'] == $vv['group_id']){
                    $list[$v['id']]['name'] = $v['name'];
                    $list[$v['id']]['arr'][$vv['id']]['id'] = $vv['id'];
                    $list[$v['id']]['arr'][$vv['id']]['name'] = $vv['name'];
                    unset($classify[$kk]);
                }
            }
        }
        //p($list);exit;
        $this->load->view('Systems/authority_add',['list'=>$list,'li'=>json_encode($list)]);
    }


    //权限增加操作
    public function authority_do()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }

        if ($this->input->is_ajax_request()) {
            $request = $this->input->post(['module_id','classify_id','name','code']);
            $this->load->database();
            try {
                $this->db->query('insert into admin_authority (module_id,classify_id,name,code) values('.$request['module_id'].','.$request['classify_id'].',"'.$request['name'].'","'.$request['code'].'")');
            } catch (\Exception $e) {
                log_message('error',$e->getMessage());
                $this->ajax_return(0);
            }
            $this->ajax_return(1);
        }
    }

    //权限修改页面
    public function authority_edit()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            show_error('暂无权限');
        }
        $id = $this->input->get('id');
        $this->load->database();
        $query = $this->db->query('select * from admin_authority where id='.$id);
        $result = $query->result_array();
        $this->load->view('Systems/authority_edit',['vo'=>$result[0]]);
    }


    //权限修改处理
    public function authority_edit_do()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }

        if ($this->input->is_ajax_request()){
            $this->load->database();
            $request = $this->input->post(['id','name','code']);
            try {
                $this->db->query('update admin_authority set name="'.$request['name'].'",code="'.$request['code'].'" where id='.$request['id']);
            } catch (\Exception $e) {
                log_message('error',$e->getMessage());
                $this->ajax_return(0);
            }
            $this->ajax_return(1);
        }
    }

    //权限删除
    public function authority_del()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            $this->ajax_return(999);
        }

        if($this->input->is_ajax_request()){
            $id = $this->input->post('id');
            $this->load->database();
            try{
                $this->db->query('delete from admin_authority where id='.$id);
            }catch(\Exception $e){
                log_message('error',$e->getMessage());
                $this->ajax_return(0);
            }
            $this->ajax_return(1);
        }
    }

}